/**
* 意见反馈提交页面
* 功能：
* 1. 提供意见反馈表单，包含标题、类型、内容、图片上传等字段
* 2. 支持表单验证、图片上传、匿名提交等功能
* 3. 提供友好的用户交互和错误提示
* 4. 支持表单数据的本地验证和提交确认
*/
<template>
    <view class="submit-page" :style="pageStyle">
        <!-- 头部区域 -->
        <page-header class="header" title="意见反馈" :backgroundColor="headerBgColor">
        </page-header>

        <!-- 内容区域 -->
        <view class="content">
            <form @submit="handleSubmitFormButtonClick">
                <!-- 意见标题：必填，5-20字 -->
                <view class="form-item">
                    <text class="form-label required">意见标题</text>
                    <input class="form-input" type="text" placeholder="简明扼要的标题（5-20字）" v-model="formData.title"
                        :maxlength="20" @blur="validateTitle" />
                    <view class="error-wrapper" v-if="errors.title">
                        <text class="error-tip">{{ errors.title }}</text>
                    </view>
                </view>

                <!-- 意见类型：必选，四种类型供选择 -->
                <view class="form-item">
                    <text class="form-label required">意见类型</text>
                    <view class="type-selector">
                        <view v-for="(type, index) in feedbackTypes" :key="index" class="type-item"
                            :class="{ 'selected': formData.type === type.value }" @click="selectType(type.value)">
                            <uni-icons :type="type.icon" size="18" :color="getIconColor(type.value)"></uni-icons>
                            <text>{{ type.label }}</text>
                        </view>
                    </view>
                    <view class="error-wrapper" v-if="errors.type">
                        <text class="error-tip">{{ errors.type }}</text>
                    </view>
                </view>

                <!-- 意见内容：必填，10-200字，支持字数统计 -->
                <view class="form-item">
                    <text class="form-label required">意见内容</text>
                    <textarea class="form-textarea" placeholder="请描述您遇到的问题或建议（10-200字）" v-model="formData.content"
                        :maxlength="200" @blur="validateContent" />
                    <view class="char-counter">
                        <text>{{ formData.content.length }}/200</text>
                    </view>
                    <view class="error-wrapper" v-if="errors.content">
                        <text class="error-tip">{{ errors.content }}</text>
                    </view>
                </view>

                <!-- 匿名选项：控制是否记录用户信息 -->
                <view class="form-item checkbox-item">
                    <label class="checkbox-label">
                        <switch color="#3c9cff" :checked="formData.isAnonymous" @change="toggleAnonymous" />
                        <text>匿名提交</text>
                    </label>
                    <text class="tip-text">匿名提交后将不会记录您的个人信息</text>
                </view>

                <!-- 昵称/姓名 -->
                <view class="form-item" v-if="!formData.isAnonymous">
                    <text class="form-label required">昵称/姓名</text>
                    <input class="form-input" type="text" placeholder="请输入您的昵称或姓名" v-model="formData.nickname"
                        :maxlength="20" @blur="validateNickname" />
                    <view class="error-wrapper" v-if="errors.nickname">
                        <text class="error-tip">{{ errors.nickname }}</text>
                    </view>
                </view>

                <!-- 联系方式：选填，支持手机号或邮箱 -->
                <view class="form-item" v-if="!formData.isAnonymous">
                    <text class="form-label">联系方式</text>
                    <input class="form-input" type="text" placeholder="手机号码或邮箱（选填）" v-model="formData.contact"
                        @blur="validateContact" />
                    <view class="error-wrapper" v-if="errors.contact">
                        <text class="error-tip">{{ errors.contact }}</text>
                    </view>
                </view>
            </form>
        </view>

        <!-- 底部区域 -->
        <view class="bottom-bar">
            <view class="submit-button-wrapper">
                <button class="submit-button" :class="{ 'disabled': isSubmitting || !isFormValid }"
                    :disabled="isSubmitting || !isFormValid" @click.prevent="handleSubmitFormButtonClick">
                    <view class="button-content">
                        <uni-icons v-if="isSubmitting" type="spinner-cycle" size="18" color="#fff"></uni-icons>
                        <text>{{ isSubmitting ? '提交中...' : '提交反馈' }}</text>
                    </view>
                </button>
            </view>
        </view>

        <!-- 提示消息：用于显示操作反馈 -->
        <view v-if="showToast" class="toast" :class="toastType">
            <text>{{ toastMessage }}</text>
        </view>

        <!-- 确认对话框：提交前的二次确认 -->
        <view v-if="showConfirmDialog" class="dialog-mask">
            <view class="dialog-container">
                <view class="dialog-title">
                    <text>确认提交</text>
                </view>
                <view class="dialog-content">
                    <text>提交后将无法修改，确认提交此反馈？</text>
                </view>
                <view class="dialog-buttons">
                    <button class="cancel-button" @click="handleCancelSubmitButtonClick">取消</button>
                    <button class="confirm-button" @click="handleConfirmSubmitButtonClick">确认提交</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import PageHeader from '/components/PageHeader.vue'; 

export default defineComponent({
    name: 'Submit',
    components: {
        PageHeader
    },
    setup() {
        // ===== 变量声明 =====
        const headerBgColor = ref('#ffffff');
        const headerInfo = ref(null);
        const footerInfo = ref(null);
        const pageStyle = ref({});

        const isSubmitting = ref(false);
        const showToast = ref(false);
        const toastMessage = ref('');
        const toastType = ref('info');
        const showConfirmDialog = ref(false);
        const submittedIds = ref(new Set());
        let toastTimer = null;
        let submitDebounceTimer = null;

        // 表单数据
        const formData = reactive({
            title: '',
            type: '',
            content: '',
            nickname: '',
            contact: '',
            isAnonymous: false
        });

        // 错误信息
        const errors = reactive({
            title: '',
            type: '',
            content: '',
            nickname: '',
            contact: ''
        });

        // ===== 计算属性 =====
        const isFormValid = computed(() => {
            const baseValid = formData.title.length >= 5 &&
                formData.type !== '' &&
                formData.content.length >= 10;

            // 非匿名时需要验证昵称
            if (!formData.isAnonymous) {
                return baseValid && formData.nickname.length >= 2;
            }

            return baseValid;
        });

        // ===== 反馈类型配置 =====
        const feedbackTypes = [
            { label: '功能建议', value: 0, key: 'feature', icon: 'star' },
            { label: '体验问题', value: 1, key: 'experience', icon: 'help' },
            { label: '程序故障', value: 2, key: 'bug', icon: 'info' },
            { label: '其他反馈', value: 3, key: 'other', icon: 'chat' }
        ];

        // ===== 页面交互方法 =====
        // 返回按钮点击
        const handleToBackPageButtonClick = () => {
            if (formData.title || formData.content) {
                uni.showModal({
                    title: '提示',
                    content: '您填写的内容尚未提交，确定要离开吗？',
                    success: (res) => {
                        if (res.confirm) {
                            uni.navigateBack();
                        }
                    }
                });
            } else {
                uni.navigateBack();
            }
        };

        // 表单提交按钮点击
        const handleSubmitFormButtonClick = () => {
            validateFormData();
            if (!isFormValid.value) {
                showToastMessage('请完善表单信息', 'error');
                return;
            }

            if (submitDebounceTimer) {
                clearTimeout(submitDebounceTimer);
            }

            submitDebounceTimer = setTimeout(() => {
                showConfirmDialog.value = true;
            }, 300);
        };

        // 确认提交按钮点击
        const handleConfirmSubmitButtonClick = () => {
            showConfirmDialog.value = false;
            const submitId = generateSubmitId();
            if (submittedIds.value.has(submitId)) {
                showToastMessage('请勿重复提交', 'warning');
                return;
            }

            isSubmitting.value = true;
            submitFeedbackData(submitId);
        };

        // 取消提交按钮点击
        const handleCancelSubmitButtonClick = () => {
            showConfirmDialog.value = false;
        };

        // ===== 其他方法 =====
        /**
         * 验证标题
         * 要求：5-20字
         */
        const validateTitle = () => {
            if (!formData.title) {
                errors.title = '请填写反馈标题';
            } else if (formData.title.length < 5) {
                errors.title = '标题至少需要5个字';
            } else {
                errors.title = '';
            }
        };

        /**
         * 验证内容
         * 要求：10-200字
         */
        const validateContent = () => {
            if (!formData.content) {
                errors.content = '请填写反馈内容';
            } else if (formData.content.length < 10) {
                errors.content = '内容至少需要10个字';
            } else {
                errors.content = '';
            }
        };

        /**
         * 验证联系方式
         * 支持：手机号或邮箱，选填
         */
        const validateContact = () => {
            if (formData.contact) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                const phoneRegex = /^1[3-9]\d{9}$/;

                if (!emailRegex.test(formData.contact) && !phoneRegex.test(formData.contact)) {
                    errors.contact = '请输入有效的手机号或邮箱';
                } else {
                    errors.contact = '';
                }
            } else {
                errors.contact = '';
            }
        };

        /**
         * 验证昵称
         * 要求：2-20字
         */
        const validateNickname = () => {
            if (!formData.isAnonymous) {
                if (!formData.nickname) {
                    errors.nickname = '请填写昵称或姓名';
                } else if (formData.nickname.length < 2) {
                    errors.nickname = '昵称至少需要2个字';
                } else {
                    errors.nickname = '';
                }
            }
        };

        /**
         * 选择反馈类型
         * @param {string} type - 反馈类型值
         */
        const selectType = (type) => {
            formData.type = type;
            errors.type = '';
        };

        /**
         * 切换匿名状态
         * @param {Event} e - 开关事件对象
         */
        const toggleAnonymous = (e) => {
            formData.isAnonymous = e.detail.value;
            if (formData.isAnonymous) {
                // 匿名时清空个人信息
                formData.nickname = '';
                formData.contact = '';
                errors.nickname = '';
                errors.contact = '';
            }
        };

        /**
         * 获取类型图标颜色
         * @param {string} typeValue - 反馈类型值
         * @returns {string} 图标颜色
         */
        const getIconColor = (typeValue) => {
            return formData.type === typeValue ? '#3c9cff' : '#666';
        };

        /**
         * 生成提交ID
         * 用于防止重复提交
         */
        const generateSubmitId = () => {
            return formData.title + '_' + new Date().getTime();
        };

        /**
         * 提交表单
         * 包含表单验证和防抖处理
         */
        const submitFeedbackData = (submitId) => {
            // 记录提交数据
            console.log('提交的反馈数据:', {
                title: formData.title,
                type: formData.type,
                content: formData.content,
                nickname: formData.isAnonymous ? '' : formData.nickname,
                contact: formData.isAnonymous ? '' : formData.contact,
                isAnonymous: formData.isAnonymous
            });

            showToastMessage('反馈提交成功', 'info');

            // 延迟返回
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        };

        /**
         * 显示提示消息
         * @param {string} message - 提示内容
         * @param {string} type - 提示类型：info/warning/error
         */
        const showToastMessage = (message, type = 'info') => {
            if (toastTimer) {
                clearTimeout(toastTimer);
            }

            toastMessage.value = message;
            toastType.value = type;
            showToast.value = true;

            toastTimer = setTimeout(() => {
                showToast.value = false;
            }, 2000);
        };

        /**
         * 初始化页面设备适配信息
         */
        const initDeviceAdaptation = () => { 
        };

        /**
         * 验证所有表单数据
         */
        const validateFormData = () => {
            validateTitle();
            validateContent();
            validateNickname();
            validateContact();
        };

        // ===== 生命周期钩子 =====
        onMounted(() => {
            // 初始化设备适配信息
            initDeviceAdaptation();
        });

        onUnmounted(() => {
            // 清理定时器
            if (toastTimer) {
                clearTimeout(toastTimer);
            }
            if (submitDebounceTimer) {
                clearTimeout(submitDebounceTimer);
            }
        });

        return {
            // 变量
            headerBgColor,
            formData,
            feedbackTypes,
            isSubmitting,
            errors,
            isFormValid,
            showToast,
            toastMessage,
            toastType,
            showConfirmDialog,
            pageStyle,

            // 方法
            handleToBackPageButtonClick,
            handleSubmitFormButtonClick,
            handleConfirmSubmitButtonClick,
            handleCancelSubmitButtonClick,
            validateTitle,
            validateContent,
            validateContact,
            validateNickname,
            validateFormData,
            selectType,
            toggleAnonymous,
            generateSubmitId,
            showToastMessage,
            getIconColor
        };
    }
});
</script>

<style lang="less" scoped>
.submit-page {
    width: 100vw;
    display: flex;
    flex-direction: column;
    background-color: #f8f8f8;

    .header {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        z-index: 100;
        background-color: #ffffff;
    }

    .content {
        flex: 1;
        overflow-y: auto;
        background-color: #f8f8f8;
        padding: 20rpx;

        form {
            .form-item {
                margin-bottom: 24rpx;
                position: relative;
                background-color: #fff;
                border-radius: 12rpx;
                padding: 20rpx 16rpx 24rpx;
                box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);

                .form-label {
                    display: block;
                    font-size: 28rpx;
                    color: #333;
                    margin-bottom: 12rpx;
                    font-weight: 500;
                    padding-left: 10rpx;
                    border-left: 4rpx solid #3c9cff;

                    &.required:after {
                        content: '*';
                        color: #ff4d4f;
                        margin-left: 6rpx;
                    }
                }

                .form-input {
                    width: 100%;
                    height: 76rpx;
                    background-color: #f9f9f9;
                    border-radius: 8rpx;
                    border: 1px solid #eaeaea;
                    padding: 0 20rpx;
                    box-sizing: border-box;
                    font-size: 28rpx;
                }

                .form-textarea {
                    width: 100%;
                    height: 220rpx;
                    background-color: #f9f9f9;
                    border-radius: 8rpx;
                    border: 1px solid #eaeaea;
                    padding: 16rpx;
                    box-sizing: border-box;
                    font-size: 28rpx;
                }

                .char-counter {
                    text-align: right;
                    padding: 6rpx 10rpx 0 0;
                    color: #999;
                    font-size: 24rpx;
                    height: 36rpx;
                }

                .tip-text {
                    font-size: 24rpx;
                    color: #999999;
                    margin-top: 8rpx;
                    padding-left: 10rpx;
                }

                .error-wrapper {
                    margin-top: 8rpx;

                    .error-tip {
                        font-size: 24rpx;
                        color: #ff4d4f;
                        padding: 2rpx 8rpx;
                        position: relative;
                        display: inline-block;
                        line-height: 1.4;
                    }
                }

                .type-selector {
                    display: flex;
                    flex-wrap: wrap;
                    background-color: #fff;
                    border-radius: 8rpx;
                    overflow: hidden;
                    margin-bottom: 8rpx;

                    .type-item {
                        width: 25%;
                        height: 110rpx;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        font-size: 24rpx;
                        color: #666;
                        gap: 8rpx;
                        border: 1px solid #f5f5f5;
                        box-sizing: border-box;
                        transition: all 0.3s;

                        &.selected {
                            color: #3c9cff;
                            background-color: rgba(60, 156, 255, 0.1);
                            transform: scale(1.02);
                        }
                    }
                }

                &.checkbox-item {
                    display: flex;
                    flex-direction: column;

                    .checkbox-label {
                        display: flex;
                        align-items: center;
                        font-size: 28rpx;
                        color: #333;

                        text {
                            margin-left: 12rpx;
                        }
                    }
                }
            }
        }
    }

    .bottom-bar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        height: 100rpx;
        background-color: #ffffff;
        box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
        z-index: 99;
        display: flex;
        align-items: center;
        justify-content: center;

        .submit-button-wrapper {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;

            .submit-button {
                width: 80%;
                height: 80rpx;
                border-radius: 40rpx;
                background: linear-gradient(135deg, #3c9cff 0%, #5eacff 100%);
                border: none;
                color: #ffffff;
                font-size: 32rpx;
                font-weight: 500;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
                box-shadow: 0 8rpx 16rpx rgba(60, 156, 255, 0.3);

                .button-content {
                    display: flex;
                    align-items: center;
                    gap: 8rpx;

                    text {
                        line-height: 1;
                    }
                }

                &:active {
                    transform: scale(0.98);
                    box-shadow: 0 4rpx 8rpx rgba(60, 156, 255, 0.2);
                }

                &.disabled {
                    opacity: 0.6;
                    background: linear-gradient(135deg, #cccccc 0%, #dddddd 100%);
                    box-shadow: none;
                    transform: none;
                }
            }
        }
    }

    /* 提示消息 */
    .toast {
        position: fixed;
        left: 50%;
        transform: translateX(-50%);
        top: calc(var(--status-bar-height) + 130rpx);
        padding: 20rpx 40rpx;
        border-radius: 40rpx;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        font-size: 28rpx;
        z-index: 1000;
        animation: fadeInDown 0.3s, fadeOut 0.3s 1.7s;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
        max-width: 80%;

        &.info {
            background-color: rgba(0, 0, 0, 0.7);
        }

        &.warning {
            background-color: rgba(240, 173, 78, 0.9);
        }

        &.error {
            background-color: rgba(221, 82, 77, 0.95);
        }
    }

    /* 确认对话框 */
    .dialog-mask {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.6);
        z-index: 9998;
        display: flex;
        justify-content: center;
        align-items: center;

        .dialog-container {
            width: 560rpx;
            background-color: #fff;
            border-radius: 16rpx;
            overflow: hidden;
            box-shadow: 0 6rpx 30rpx rgba(0, 0, 0, 0.1);

            .dialog-title {
                padding: 30rpx 0;
                text-align: center;
                font-size: 32rpx;
                font-weight: 500;
                color: #333;
                border-bottom: 1px solid #f0f0f0;
            }

            .dialog-content {
                padding: 40rpx 30rpx;
                text-align: center;
                font-size: 28rpx;
                color: #666;
            }

            .dialog-buttons {
                display: flex;
                border-top: 1px solid #f0f0f0;

                button {
                    flex: 1;
                    height: 90rpx;
                    margin: 0;
                    font-size: 28rpx;
                    border-radius: 0;
                    line-height: 90rpx;

                    &.cancel-button {
                        color: #666;
                        background-color: #fff;
                        border-right: 1px solid #f0f0f0;
                    }

                    &.confirm-button {
                        color: #3c9cff;
                        background-color: #fff;
                    }
                }
            }
        }
    }

    /* 动画 */
    @keyframes fadeInDown {
        from {
            opacity: 0;
            transform: translate(-50%, -20rpx);
        }

        to {
            opacity: 1;
            transform: translate(-50%, 0);
        }
    }

    @keyframes fadeOut {
        from {
            opacity: 1;
        }

        to {
            opacity: 0;
        }
    }
}
</style>